package com.fadadianqi.commons;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;

public class GetConfigFile {

    private static final Log log = LogFactory.getLog(GetConfigFile.class);

    private String filename;

    public GetConfigFile(String filename) {
        this.filename = filename;
    }

    public File get() {
        File file = new File(Constants.ROOT_PATH + "conf" + File.separator + filename);
        if (file.exists()) {
            log.info("Loaded properties: " + file.getAbsolutePath());
            return file;
        }
        log.warn("Not found " + file.getAbsolutePath());
        file = new File(Constants.WEB_INF_PATH + "conf" + File.separator + filename);
        if (file.exists()) {
            log.info("Loaded properties: " + file.getAbsolutePath());
            return file;
        }
        log.warn("Not found " + file.getAbsolutePath());
        return get0();
    }

    private File get0() {
        String _classpath = System.getProperty("java.class.path");
        String[] classpathList = _classpath.split(":");
        log.debug("_classpath: " + _classpath);
        for (String classpath : classpathList) {
            String filepath = classpath + File.separator + filename;
            File file = new File(filepath);
            if (file.exists()) {
                return file;
            }
        }
        return null;
    }
}
